package com.yl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yl.common.core.domain.AjaxResult;
import com.yl.common.exception.ServiceException;
import com.yl.common.utils.SecurityUtils;
import com.yl.common.utils.StringUtils;
import com.yl.common.utils.http.HttpUtils;
import com.yl.config.ZhiXingUrlConfig;
import com.yl.domain.ConferenceApplyDO;
import com.yl.domain.UserDO;
import com.yl.domain.dto.StudentDTO;
import com.yl.framework.web.service.SysLoginService;
import com.yl.mapper.ConferenceApplyMapper;
import com.yl.mapper.ConferenceMapper;
import com.yl.mapper.UserMapper;
import com.yl.service.ZhiXingService;
import com.yl.utils.CommonUtils;
import com.yl.utils.HttpClientUtil;
import com.yl.utils.RSACrypot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.PublicKey;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ZhiXingServiceImpl implements ZhiXingService {
    private static final Logger log = LoggerFactory.getLogger(ZhiXingServiceImpl.class);
    @Resource
    ZhiXingUrlConfig zhiXingUrlConfig;
    @Resource
    UserMapper userMapper;
    @Resource
    SysLoginService sysLoginService;
    @Resource
    ConferenceApplyMapper conferenceApplyMapper;

    /**
     * 生成token 用于调用职行API，
     * token 生成规则 agent-1-时间戳
     *
     * @param agentId
     * @author : y
     * @date :  2024/6/24 14:06
     */
    @Override
    public String getTokenByAgentId(Long agentId) {
        try {
            // todo agentId =1
            agentId = 1L;
            // 获取公钥
            PublicKey publicKey = RSACrypot.getPublicKey(zhiXingUrlConfig.getPublicKey());
            // 获取10位的时间戳
            Instant instant = Instant.now();
            long epochSecond = instant.getEpochSecond();
            String spliceString = "token-" + agentId + "-" + epochSecond;
            log.info("生成token前的字符串={}", spliceString);
            // 生成token
            String token = RSACrypot.encryptWithPublicKey(spliceString, publicKey);
            log.info("生成的token={}", token);
            return token;
        } catch (Exception e) {
            log.info("获取公钥失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建主题
     *
     * @param name         主题                              必填
     * @param career_msg   说明。类似职业解析            不必填
     * @param label        类型标签--职行新增职业的职业类型     必填
     *                     question_num 固定值1                    必填
     * @param career_photo 职业图片                  不必填
     * @return code
     * @author : y
     * @date :  2024/6/24 11:10
     **/
    @Override
    public AjaxResult saveDiscussion(String name, String career_msg, String label, String career_photo) {
        // 生成token
        String token = getTokenByAgentId(17L);
        // 拼接JSON
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", name);
        if (StringUtils.isNotBlank(career_msg)) {
            map.put("career_msg", career_msg);
        }
        map.put("question_num", 1);
        map.put("label", label);
        // 发布
        map.put("is_release ", true);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getSavediscussion();
        try {
            log.info("请求url={},请求参数={}", url, map);
            String post = HttpClientUtil.doPostFormData(url, map, token);
            log.info("获取到的结果为{}", post);
            // 处理返回值
            AjaxResult ajaxResult = JSONObject.parseObject(post, AjaxResult.class);
            return ajaxResult;
        } catch (IOException e) {
            log.info("新增职行失败，失败原因={}", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改 主题
     *
     * @param name
     * @param career_msg
     * @param label
     * @param career_photo
     * @author : y
     * @date :  2024/6/25 9:20
     */
    @Override
    public AjaxResult updateDiscussion(String name, String career_msg, String label, String career_photo, Long id) {
        // 生成token
        String token = getTokenByAgentId(17L);
        AjaxResult result = new AjaxResult();
        // 拼接JSON
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("career_msg", career_msg);
        map.put("label", label);
        map.put("is_release ", true);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getUpdatediscussion() + id;
        log.info("修改主题接口：请求url={},请求参数={}", url, map);
        try {
            String post = HttpClientUtil.doPut(url, map, token);
            log.info("修改主题接口获取到的结果为{}", post);
            // 处理返回值
            result = JSONObject.parseObject(post, AjaxResult.class);
            return result;
        } catch (IOException e) {
            log.info("修改主题接口报错，报错代码={},具体原因={}", result.get("code"), result.get("msg"));
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param page
     * @param size
     * @author : y
     * @date :  2024/6/26 10:10
     */
    @Override
    public AjaxResult getDiscussion(Integer page, Integer size) {
        // 生成token
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getGetDiscussion();

        String result = HttpClientUtil.doGetNotParam(url, token);
        AjaxResult ajaxResult = JSONObject.parseObject(result, AjaxResult.class);
        return ajaxResult;
    }


    /**
     * 删除 主题
     *
     * @param id
     * @author : y
     * @date :  2024/6/26 10:21
     */
    @Override
    public AjaxResult deleteDiscussion(Long id) {
        // 生成token
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getDeletediscussion();
        url = url + "/" + id;
        try {
            log.info("删除主题入参=={}", url);
            String delete = HttpClientUtil.doDelete(url, token);
            log.info("删除主题返回参数={}", delete);
            AjaxResult result = JSONObject.parseObject(delete, AjaxResult.class);
            return result;
        } catch (IOException e) {
            log.info("删除主题失败，失败原因={}", e.getMessage());
            e.printStackTrace();
        }

        return AjaxResult.error("操作失败");
    }


    /**
     * 获取主题详情
     *
     * @param id
     * @author : y
     * @date :  2024/6/26 16:49
     */
    @Override
    public AjaxResult getDiscussionById(Long id) {
        // 生成token
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getGetdiscussiondetail() + id;
        log.info("获取主题详情入参url=={}", url);
        String delete = HttpClientUtil.doGetNotParam(url, token);
        log.info("获取主题详情返回参数={}", delete);
        AjaxResult result = JSONObject.parseObject(delete, AjaxResult.class);
        return result;
    }

    /**
     * 获取题目的标签列表
     *
     * @author : y
     * @date :  2024/6/25 14:20
     **/
    @Override
    public AjaxResult getTiKuTagList() {
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getGetTiKuTagList();
        log.info("修改主题接口：请求url={}", url);
        String param = HttpClientUtil.doGetNotParam(url, token);
        if (StringUtils.isBlank(param)) {
            return AjaxResult.error("获取失败");
        }
        AjaxResult result1 = com.alibaba.fastjson2.JSONObject.parseObject(param, AjaxResult.class);
        log.info("获取题目的标签列表返回值={}", result1);
        return result1;
    }


    /**
     * 创建题目
     *
     * @param text         题目内容 会生成数字人
     * @param ans_analysis 参考答案
     * @param level        基础/进阶
     * @param skill_tag    标签 list
     * @param career_id    职业id
     * @author : y
     * @date :  2024/6/25 16:36
     **/
    @Override
    public AjaxResult createTiKu(String text, String ans_analysis, String level, List<Long> skill_tag, Long career_id) {
        String token = getTokenByAgentId(17L);
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("text", text);
        jsonParam.put("ans_analysis", ans_analysis);
        jsonParam.put("level", level);
        jsonParam.put("skill_tag", skill_tag);
        jsonParam.put("career_id", career_id);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getCreateTiku();
        log.info("创建主题接口：请求url={},\n参数={}\r\ntoken={}", url, jsonParam, token);
        String sendPost = HttpClientUtil.sendPost(url, jsonParam.toString(), token);
        log.info("创建题目返回结果result={}", sendPost);
        AjaxResult result = com.alibaba.fastjson2.JSONObject.parseObject(sendPost, AjaxResult.class);
        log.info("格式化后的结果={}", result);
        return result;
    }

    /**
     * 获取学生列表
     *
     * @param page
     * @param pageSize
     * @author : y
     * @date :  2024/6/27 16:19
     */
    @Override
    public AjaxResult getStudentPage(Integer page, Integer pageSize) {
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getGetStudentPage();
        String result = HttpClientUtil.doGetNotParam(url, token);
        log.info("获取学生列表返回参数==result={}", result);
        AjaxResult ajaxResult = JSONObject.parseObject(result, AjaxResult.class);
        return ajaxResult;
    }


    /**
     * 生成数字人
     *
     * @param content 需要生成的视频
     * @author : y
     * @date :  2024/6/27 16:29
     **/
    @Override
    public AjaxResult createHiHuman(String content) {
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getSaveDiHuman();
        log.info("生成数字人视频接口入参 content={}", content);
        HashMap<String, Object> map = new HashMap<>();
        map.put("content", content);
        String sendPost = "";
        try {
            sendPost = HttpClientUtil.sendPostByJson(url, map, token);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("生成数字人视频接口result={}", sendPost);
        return JSONObject.parseObject(sendPost, AjaxResult.class);
    }

    /**
     * 根据ID查询数字人视频
     *
     * @param id
     * @author : y
     * @date :  2024/6/27 16:30
     */
    @Override
    public AjaxResult getHiHuman(Long id) {
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getGetDiHuman();
        // JSONObject jsonParam = new JSONObject();
        // jsonParam.put("id", id);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id + "");
        log.info("获取数字人视频地址入参 id={}", id);
        String sendPost = HttpClientUtil.doGet(url, map, token);
        log.info("获取数字人视频地址返回参数result={}", sendPost);
        return JSONObject.parseObject(sendPost, AjaxResult.class);
    }

    /**
     * 验证账号密码
     *
     * @param account  账号
     * @param password 密码
     * @param type
     * @type 类型(student / admin)
     * @author : y
     * @date :  2024/6/28 10:04
     **/
    @Override
    public AjaxResult verifyAccount(String account, String password, String type) {
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password) || StringUtils.isBlank(type)) {
            return AjaxResult.error("参数为空登录失败");
        }
        String token = getTokenByAgentId(1L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getVerifyAccount();
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("account", account);
        jsonParam.put("password", password);
        jsonParam.put("type", type);
        log.info("验证职行账号密码入参 jsonParam={}", jsonParam);
        String sendPost = HttpClientUtil.sendPost(url, jsonParam.toString(), token);
        log.info("验证职行账号密码返回参数 result={}", sendPost);
        AjaxResult result = JSONObject.parseObject(sendPost, AjaxResult.class);
        if (result != null && result.get("code").equals(200)) {
            log.info("开始验证本系统账号密码---------------------");
            Map<String, Object> map = JSONObject.parseObject(result.get("data").toString(), Map.class);
            // 保存用户信息
            UserDO user = userMapper.selectOne(Wrappers.<UserDO>lambdaQuery().eq(UserDO::getUserName, account).eq(UserDO::getIdentity, type).eq(UserDO::getAgentId, 17L));
            if (user == null) {
                user = new UserDO();
                user.setUserName(account);
                user.setPassword(SecurityUtils.encryptPassword(password));
                user.setIdentity(type);
                user.setAgentId(17L);
                user.setSchoolName(map.get("school").toString());
                user.setNickName(map.get("name").toString());
                userMapper.insert(user);
            } else {
                // 同步数据
                user.setUserName(account);
                user.setPassword(SecurityUtils.encryptPassword(password));
                user.setIdentity(type);
                user.setAgentId(17L);
                user.setSchoolName(map.get("school").toString());
                user.setNickName(map.get("name").toString());
                userMapper.updateById(user);
            }
            // 登录
            String tokens = sysLoginService.loginNotVerify(account, password);
            result.put("token", tokens);
        }
        return result;
    }


    /**
     * 2.3.2 批量创建面试场次/同时返回题目
     *
     * @param careerId
     * @param users
     * @author : y
     * @date :  2024/7/10 15:30
     */
    @Override
    public AjaxResult batchCreateSession(Long careerId, List<StudentDTO> users) {
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getCreateBatchSession();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("career_id", careerId);
        jsonObject.put("users", users);
        log.info("批量创建会议传参======{}", jsonObject);
        String sendPost = HttpClientUtil.sendPost(url, jsonObject.toString(), token);
        log.info("批量创建会议返回参数==={}", sendPost);
        return JSONObject.parseObject(sendPost, AjaxResult.class);
    }


    /**
     * 创建面试报告
     *
     * @param sessionId
     * @author : y
     * @date :  2024/7/10 16:23
     */
    @Override
    public AjaxResult createReport(Long sessionId) {
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl()+"discussion/"+sessionId+"/report";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mark", true);
        String sendPost = HttpClientUtil.sendPost(url, jsonObject.toString(), token);
        log.info("创建面试报告====返回参数={}", sendPost);
        return JSONObject.parseObject(sendPost, AjaxResult.class);
    }

    /**
     * 获取面试报告
     *
     * @author : y
     * @date :  2024/7/10 16:32
     */
    @Override
    public AjaxResult getReport(Long sessnionId, Long conferenceId) {
        String token = getTokenByAgentId(17L);
        // 查询学生的sessionId
        // ConferenceApplyDO studentApply = conferenceApplyMapper.selectOne(Wrappers.<ConferenceApplyDO>lambdaQuery().eq(ConferenceApplyDO::getConferenceId, conferenceId).eq(ConferenceApplyDO::getId, studentId));
        // if (studentApply == null) {
        //     return AjaxResult.error("学生未参加该会议");
        // }
        String url = zhiXingUrlConfig.getTestUrl() + "discussion/" + sessnionId + "/report";
        log.info("获取学生报告url====={},token - {}",url,token);
        String sendPost = HttpClientUtil.doGet(url, token);
        log.info("获取学生报告返回参数result={}", sendPost);
        return JSONObject.parseObject(sendPost, AjaxResult.class);
    }

    /**
     * 2.3.3 每个同学回答完成上传答案信息
     *
     * @param param
     * @author : y
     * @date :  2024/7/14 16:38
     */
    @Override
    public AjaxResult ask_finish(String param) {
        String token = getTokenByAgentId(17L);
        String url = zhiXingUrlConfig.getTestUrl() + zhiXingUrlConfig.getAskFinish();
        log.info("每个同学回答完成上传答案信息 =[入参]：{}", param);
        String sendPost = HttpClientUtil.sendPost(url, param, token);
        log.info("每个同学回答完成上传答案信息====【返参】={}", sendPost);
        return JSONObject.parseObject(sendPost, AjaxResult.class);
    }
}
